package com.frogs.ucenter.v1.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.frogs.api.wechat.util.SendMessageUtil;
import com.frogs.framework.component.image.ImagesResize;
import com.frogs.framework.component.image._enum.ImageEnum;
import com.frogs.framework.component.image._enum.ImgStatusEnum;
import com.frogs.framework.util.ImageUtil;
import com.frogs.framework.util.ImageUtil.ImageInfo;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.file.FileUtil;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.dao.CommonPhotoDao;
import com.frogs.ucenter.dao.CommonPhotoOperLogDao;
import com.frogs.ucenter.entity.CommonPhoto;
import com.frogs.ucenter.entity.CommonPhotoOperLog;
import com.frogs.ucenter.v1.request.DownloadImgRequest;
import com.frogs.ucenter.v1.request.ImagesDeleteRequest;
import com.frogs.ucenter.v1.request.ImagesListRequest;
import com.frogs.ucenter.v1.request.UploadImgRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.EmptyResponse;
import com.frogs.ucenter.v1.response.ListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UploadImgResponse;
import com.frogs.ucenter.v1.service.UploadService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Service(ApiConstants.VERSION+"uploadService")
public class UploadServiceImpl implements UploadService {
	
	private static final Logger log = LoggerFactory.getLogger(UploadServiceImpl.class);
	
	private static ResourceBundle imgUploadBundle;
	private static ResourceBundle ftpBundle;
	private static final String imgUploadConfigPath = "imgUploadConfig";
	private static final String ftpConfigPath = "ftp-config";
	private static String domain;
	private static String downloadDomain;
	
	@Resource(name="commonPhotoDao")
	private CommonPhotoDao commonPhotoDao;
	@Resource(name="commonPhotoOperLogDao")
	private CommonPhotoOperLogDao photoOperLogDao;
	@Resource
	private RequestApiHelper requestApiHelper;
	
	static{
		imgUploadBundle = PropertyResourceBundle.getBundle(imgUploadConfigPath);
		ftpBundle = PropertyResourceBundle.getBundle(ftpConfigPath);
		domain = imgUploadBundle.getString("static.domain_url");
		downloadDomain = imgUploadBundle.getString("download.domain_url");
	}
	
	@Override
	public List<Map<String,String>> uploadImages( HttpServletRequest httpRequest, String basicPath,
			String urlBasicPath,String domain,Request request) throws Exception  {
		
		
		UploadImgRequest uploadRequest = (UploadImgRequest)request;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpRequest;
		Iterator<String> it = multipartRequest.getFileNames();
        List<Map<String,String>> paths = new ArrayList<Map<String,String>>();
        String refResource = uploadRequest.getRefResource(); 
        int resourceId = uploadRequest.getResourceId();
        int forceRenew = uploadRequest.getForceRenew();
        //图片上传方式：默认不加水印
        int type = uploadRequest.getType();
        boolean needResize = true;
        
        while (it.hasNext()) {
            String oldFileName = (String) it.next();
            MultipartFile multipartFile = multipartRequest.getFile(oldFileName);
            String fileName =  uploadRequest.getFileName();
            String secDir = uploadRequest.getDirect();
            
            //若传具体路径跟文件名，则按照文件名生成
            if(uploadRequest.getResize() == ImgStatusEnum.UN_NEED_RESIZE.getId()) {
            	needResize = false;
            } else {
            	needResize = true;
            }
            
            if(StringUtil.isEmpty(secDir) || StringUtil.isEmpty(fileName)) {
            	String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            	fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
            	secDir = new SimpleDateFormat("yyyy/MM").format(new Date());
            }
            		
    		Map<String,String> pathMap = new HashMap<String,String>();
    		String filePath = FileUtil.getSaveFilePath(basicPath, getRelateDirPath( urlBasicPath, secDir),  fileName);
    		
    		try{
    			String hexCode = ImageUtil.getMd5Hex(multipartFile.getBytes());
    			Map<String, Object> params = new HashMap<String, Object>();
    			params.put("eqHexCode", hexCode);
    			params.put("eqStatus", ImgStatusEnum.IMG_NOT_DELETE.getId());
    			
    			List<CommonPhoto> photos = commonPhotoDao.selectByMap(params, false);
    			String fileUrl=null;
    			if(null != photos && photos.size() > 0 && forceRenew == ImgStatusEnum.NOT_FORCE_RENEW.getId()) {
    				CommonPhoto photo = photos.get(0);
    				fileUrl = photo.getImgPath();
    			} else {
	    			File file = new File(filePath);
	    			multipartFile.transferTo(file);
	    			//加水印
	    			if(type == ImageEnum.IMG_WITH_MARK.getId()) {
	    				ImageInfo info = ImageUtil.getImageInfo(file);
	    				ImageUtil.drawImageMark(filePath, filePath, httpRequest.getRealPath("/") + "/ico/logo.png", info.getWidth(), info.getHeight(), 0.3f);
	    			}
	    			
	    			//服务器上的路径
	    			fileUrl=this.getUrlPath(domain, getRelateDirPath(urlBasicPath, secDir), fileName);
	    			//存在时更新
	    			CommonPhoto photoBean;
	    			if(null != photos && photos.size() > 0) {
	    				photoBean = photos.get(0);
		    			photoBean.setCreateDate(new Date());
		    			photoBean.setImgPath(fileUrl);
		    			photoBean.setRefResource(refResource);
		    			photoBean.setResourceId(resourceId);
		    			photoBean.setCreateUserId(uploadRequest.getUserId());
		    			photoBean.setCreateUserName(uploadRequest.getUserName());
		    			photoBean.setHexCode(hexCode);
		    			photoBean.setLocalPath(basicPath + getRelateDirPath( urlBasicPath, secDir));
		    			photoBean.setServerPath(getRelateDirPath( urlBasicPath, secDir));
		    			photoBean.setStatus(ImgStatusEnum.IMG_NOT_DELETE.getId());
		    			photoBean.setFileName(fileName);
		    			commonPhotoDao.update(photoBean);
	    			} else {
	    				photoBean = new CommonPhoto();
		    			photoBean.setCreateDate(new Date());
		    			photoBean.setImgPath(fileUrl);
		    			photoBean.setRefResource(refResource);
		    			photoBean.setResourceId(resourceId);
		    			photoBean.setCreateUserId(uploadRequest.getUserId());
		    			photoBean.setCreateUserName(uploadRequest.getUserName());
		    			photoBean.setHexCode(hexCode);
		    			photoBean.setLocalPath(basicPath + getRelateDirPath( urlBasicPath, secDir));
		    			photoBean.setServerPath(getRelateDirPath( urlBasicPath, secDir));
		    			photoBean.setStatus(ImgStatusEnum.IMG_NOT_DELETE.getId());
		    			photoBean.setFileName(fileName);
		    			commonPhotoDao.insert(photoBean);
	    			}
	    			
	    			recordOperLog(ImgStatusEnum.IMG_OPER_UPLOAD.getId(),photoBean.getPhotoId(),
	    					uploadRequest.getUserId(),uploadRequest.getUserName(),
	    					uploadRequest.getIp(), fileName );
	    			
	    			if(needResize) {
	    				imgResize(filePath, fileName);
	    			}
	    			
    			}
    			
    			pathMap.put("original", fileUrl);
    			if(needResize) {
					pathMap.put(ImageEnum.IMG_LARGE.getName(), makeNewPath(fileUrl,ImageEnum.IMG_LARGE.getName()));
					pathMap.put(ImageEnum.IMG_MIDDLE.getName(), makeNewPath(fileUrl,ImageEnum.IMG_MIDDLE.getName()));
					pathMap.put(ImageEnum.IMG_SMALL.getName(),makeNewPath(fileUrl,ImageEnum.IMG_SMALL.getName()));
    			}
    			paths.add(pathMap);
    			
    		} catch (Exception e) {
    			log.error("func[{}] request[{}] exception[{}] desc[fail]",
    					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
    						request,Arrays.deepToString(e.getStackTrace()) });
    			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
    		}
        }
        return paths;
	}
	
	/**
	 * 执行图片上传操作
	 */
	@Override
	public Response doUploadImg(HttpServletRequest httpRequest,Request request) throws Exception{
		try {
			UploadImgRequest uploadRequest = (UploadImgRequest)request;
			String refResource= uploadRequest.getRefResource();
			String basicPath = "";
			String urlBasicPath = "";
			
			try {
				basicPath = ftpBundle.getString(refResource + ".basicPath");
				urlBasicPath = ftpBundle.getString(refResource + ".urlBasicPath");
			} catch (Exception e) {
				basicPath = ftpBundle.getString("basicPath");
				urlBasicPath = ftpBundle.getString("urlBasicPath");
			}
			
			List<Map<String,String>> paths = uploadImages(httpRequest, basicPath, urlBasicPath, domain,request);
			UploadImgResponse returnResponse = new UploadImgResponse();
			returnResponse.putImgPaths(paths);
			return returnResponse;
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	/**
	 * 获取库中图片路径
	 */
	@Override
	public Response getUploadedImg(HttpServletRequest httpRequest,
			Request request)  throws Exception{
		try{
			String refResource = ((UploadImgRequest)request).getRefResource(); 
			int resourceId = ((UploadImgRequest)request).getResourceId();
			List<String> pathList = commonPhotoDao.listPathsByResource(refResource, resourceId);
			UploadImgResponse returnResponse = new UploadImgResponse();
			returnResponse.putImgPaths(pathList);
			return returnResponse;
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}
	
	public String makeNewPath(String basePath,String imgSize) {
		int index = basePath.lastIndexOf("."); 
		return basePath.substring(0, index) + "_" + imgSize + basePath.substring(index);
	}

	@Override
	public Response listUploadedImg(HttpServletRequest httpRequest,
			Request request)  throws Exception{
		ImagesListRequest listRequest = (ImagesListRequest)request;
		String basicPath;
		String urlBasicPath;
		String refResource = listRequest.getRefResource();
		String direct = listRequest.getDirect();
		String back_suffix;
		try {
			basicPath = ftpBundle.getString(refResource + ".basicPath");
			urlBasicPath = ftpBundle.getString(refResource + ".urlBasicPath");
		} catch (Exception e) {
			basicPath = ftpBundle.getString("basicPath");
			urlBasicPath = ftpBundle.getString("urlBasicPath");
		}
		back_suffix = ftpBundle.getString("back_suffix");
		
		String path = basicPath + urlBasicPath + direct;
		try {
			File fileDir = new File(path);
			if(!fileDir.exists()) {
				throw new Exception("文件路径不存在");
			}
			if(!fileDir.isDirectory()) {
				throw new Exception("此目录非文件夹");
			}
			
			File[] files = fileDir.listFiles();
			List<String> fileNames = new ArrayList<String>(); 
			for(File f : files) {
				if(f.getName().indexOf("_" + back_suffix) != -1 || f.getName().indexOf('.') == -1) {
					continue;
				}
				fileNames.add(f.getName());
			}
			if(fileNames.isEmpty()) {
				return new EmptyResponse(); 
			} else {
				ListResponse<String> listResponse = new ListResponse<String>();
				listResponse.setList(fileNames);
				listResponse.setTip("获取列表成功");
				return listResponse;
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response deleteUploadedImg(HttpServletRequest httpRequest,
			Request request) throws Exception {
		ImagesDeleteRequest deleteRequest = (ImagesDeleteRequest)request;
		Response response = new DefaultResponse();
		String basicPath;
		String urlBasicPath;
		String refResource = deleteRequest.getRefResource();
		String direct = deleteRequest.getDirect();
		String back_suffix;
		try {
			basicPath = ftpBundle.getString(refResource + ".basicPath");
			urlBasicPath = ftpBundle.getString(refResource + ".urlBasicPath");
		} catch (Exception e) {
			basicPath = ftpBundle.getString("basicPath");
			urlBasicPath = ftpBundle.getString("urlBasicPath");
		}
		back_suffix = ftpBundle.getString("back_suffix");
		try {
			if(!FileUtil.isDirectory(basicPath + urlBasicPath + direct)) {
				throw new Exception("文件路径不正确");
			}
			
			String filePath = basicPath + urlBasicPath + direct + deleteRequest.getFileName();
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("eqStatus", ImgStatusEnum.IMG_NOT_DELETE.getId());
			params.put("eqLocalPath", basicPath + urlBasicPath + direct);
			List<CommonPhoto> photos = commonPhotoDao.selectByMap(params, false);
			if(!FileUtil.isExist(filePath)) {
				throw new Exception("目标文件不存在");
			} else {
				int photoId = -1;
				CommonPhoto photo = null;
				if(photos.size() > 0) {
					photo = photos.get(0);
					photoId = photos.get(0).getPhotoId();
				}
				FileUtil.rename(filePath, makeNewPath(filePath, back_suffix));
				recordOperLog(ImgStatusEnum.IMG_OPER_DELETE.getId(), 
						photoId,deleteRequest.getUserId(), deleteRequest.getUserName(), 
						deleteRequest.getIp(), deleteRequest.getFileName() );
				if(null != photo) {
					photo.setStatus(ImgStatusEnum.IMG_DELETE.getId());
					commonPhotoDao.update(photo);
				}
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		response.setTip("删除成功");
		return response;
	}
	
	/**
	 * 记录操作日志
	 */
	private void recordOperLog(int operType, int photoId, int userId, String userName, String ip, String fileName ) {
		CommonPhotoOperLog operlog = new CommonPhotoOperLog();
		operlog.setCreateTime(new Date());
		operlog.setIp(ip);
		operlog.setOperType(operType);
		operlog.setPhotoId(photoId);
		operlog.setUserId(userId);
		operlog.setUserName(userName);
		operlog.setUuid("-");
		operlog.setFileName(fileName);
		photoOperLogDao.insert(operlog);
	}
	
	/**
	 * 获取图片链接
	 */
	@Override
	public String getUrlPath(String domain, String relateDir, String fileName){
		String path = new StringBuffer(relateDir).append(fileName).toString();
		return domain + path.replace("//", "/");
	}
	
	/**
	 * 压缩图片
	 */
	@Override
	public void imgResize(String filePath,String fileName){
		
		Map<String,String> sizeMap = new HashMap<String,String>();

		sizeMap.put(ImageEnum.IMG_LARGE.getName(),imgUploadBundle.getString(ImageEnum.IMG_LARGE.getName()));
		sizeMap.put(ImageEnum.IMG_MIDDLE.getName(),imgUploadBundle.getString(ImageEnum.IMG_MIDDLE.getName()));
		sizeMap.put(ImageEnum.IMG_SMALL.getName(),imgUploadBundle.getString(ImageEnum.IMG_SMALL.getName()));

		ImagesResize resizeImage = new ImagesResize(new File(filePath) , 0, sizeMap);
		resizeImage.run();
	}
	
	/**
	 * 获取文件类型
	 */
	@Override
	public String getFileSuffix(MultipartFile multipartFile){
		return multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
	}
	
	/**
	 * 判断图片类型
	 */
	@Override
	public int getFileType(String suffix){
		int type = -1;
		if(".bmp.jpg.gif.tiff.png".indexOf(suffix) != -1){ //图片文件
			type = 1;
		} else if(".csv".indexOf(suffix) != -1){//淘宝的csv文件
			type = 2;
		} else if(".xlsx".indexOf(suffix)!=-1||".xls".indexOf(suffix)!=-1||".txt".indexOf(suffix)!=-1){//exal表格
			type = 3;
		}
		return type;
	}
	
	/**
	 * 组装图片目录
	 * @param urlBasicPath
	 * @param yyyymm
	 * @return
	 */
	private static String getRelateDirPath(String urlBasicPath, String yyyymm){
		String relateDir = null;
		relateDir = urlBasicPath+"/" + yyyymm + "/";
		return relateDir.replace("//", "/");
	}

	

	@Override
	public Response doDownloadImg(Request request) {
		ShowResponse<JSONObject> response = new ShowResponse<JSONObject>();
		try {
			DownloadImgRequest downloadRequest = (DownloadImgRequest) request;
			String basicPath = "";
			String urlBasicPath = "";
			try {
				basicPath = ftpBundle.getString("picture.basicPath");
				urlBasicPath = ftpBundle.getString("picture.urlBasicPath");
			} catch (Exception e) {
				basicPath = ftpBundle.getString("basicPath");
				urlBasicPath = ftpBundle.getString("urlBasicPath");
			}
			
			String secDir = new SimpleDateFormat("yyyy/MM").format(new Date());
			String fileName = "";
			 
			 //获取文件要存储的绝对路径
			String filePath = getRelateDirPath( basicPath, getRelateDirPath( urlBasicPath, secDir));
			File logoSaveFile = new File(filePath);
			if (!logoSaveFile.exists())
				logoSaveFile.mkdirs();  
			
			int openId = downloadRequest.getOpenPlatformId();
			String token = requestApiHelper.getAccessToken(openId);
			String mediaId = downloadRequest.getMediaId();
			Object resul = SendMessageUtil.downloadMedia(token, mediaId);
			String result = "";
			if(resul instanceof JSONObject) {
				result = (String)((JSONObject) resul).toJSONString();
			} else {
				result = resul.toString();
			}
			
			byte[] pic = File2byte(result);
			fileName = (result).split("\\\\")[(result).split("\\\\").length-1];
			String fileUrl=null;     //服务器上的路径
			
			Map<String, Object> params = new HashMap<String, Object>();
			try{
    			String hexCode = ImageUtil.getMd5Hex(pic);
    			params.put("eqHexCode", hexCode);
    			params.put("eqStatus", ImgStatusEnum.IMG_NOT_DELETE.getId());
    			
    			List<CommonPhoto> photos = commonPhotoDao.selectByMap(params, false);
    			
    			CommonPhoto photoBean;
    			
    			if(null != photos && photos.size() > 0) {   //已经下载
    				CommonPhoto photo = photos.get(0);
    				fileUrl = photo.getImgPath(); 
    				//存在时更新
    				photoBean = photos.get(0);
	    			photoBean.setCreateDate(new Date());
	    			photoBean.setImgPath(fileUrl);
	    			photoBean.setHexCode(hexCode);
	    			photoBean.setLocalPath(filePath);
	    			photoBean.setServerPath(getRelateDirPath( urlBasicPath, secDir+"/picture"));
	    			photoBean.setStatus(ImgStatusEnum.IMG_NOT_DELETE.getId());
	    			photoBean.setFileName(fileName);
	    			commonPhotoDao.update(photoBean);
    			} else {
    				
    				FileUtil.move(result, filePath, true);  
    				//服务器上的路径
    				fileUrl=this.getUrlPath(downloadDomain, getRelateDirPath(urlBasicPath, secDir+"/picture"), fileName);
    				
    				photoBean = new CommonPhoto();
	    			photoBean.setCreateDate(new Date());
	    			photoBean.setImgPath(fileUrl);
	    			photoBean.setHexCode(hexCode);
	    			photoBean.setLocalPath(filePath);
	    			photoBean.setServerPath(getRelateDirPath( urlBasicPath, secDir+"/picture"));
	    			photoBean.setStatus(ImgStatusEnum.IMG_NOT_DELETE.getId());
	    			photoBean.setFileName(fileName);
	    			commonPhotoDao.insert(photoBean);
    			}
    		} catch (Exception e) {
    			log.error("func[{}] request[{}] exception[{}] desc[fail]",
    					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
    						request,Arrays.deepToString(e.getStackTrace()) });
    			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
    		}		
			System.gc();
			FileUtil.deleteFile(result);    //删除本地临时文件
			JSONObject object = new JSONObject();
			object.put("imgUrl", fileUrl);
			response.setInfo(object);
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		
		return response; 
	}
	
	//将文件转换为字节流数组
	private  byte[] File2byte(String filePath){  
        byte[] buffer = null;  
        try{  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1){  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }catch (FileNotFoundException e){  
        	log.error("func[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
        			filePath, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage()); 
        }  
        catch (IOException e){  
        	log.error("func[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
        			filePath, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage()); 
        }  
        return buffer;  
    }  
	
}